//
//  CommentViewController.m
//  Four_Fit_New
//
//  Created by lanou on 16/7/14.
//  Copyright © 2016年 xmaz. All rights reserved.
//

#import "CommentViewController.h"
#import "Community.h"
#import "CommunityCell.h"
#import "comment.h"
#import "CommentCell.h"
#import "CommunityUserViewController.h"
#import "ThumbButton.h"
#import "UserDetailedModel.h"
#import <UIButton+WebCache.h>
#import "LikeInfoViewController.h"

#define kThumbButtonHasFailWithThumb @"kThumbButtonHasFailWithThumb"
@interface CommentViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSapce;
@property (weak, nonatomic) IBOutlet UIButton *button;
/** 存放点赞用户头像网址 */
@property (nonatomic, strong) NSMutableArray *likeArray;
/**  */
@property (nonatomic, strong) NSMutableArray *dataArray;
/**  */
@property (nonatomic, strong) NSMutableArray *array;
/** 存放点赞用户的id */
@property (nonatomic, strong) NSMutableArray *idArray;
/** 存放点赞用户的名字 */
@property (nonatomic, strong) NSMutableArray *nameArray;
/** 个人简介 */
@property (nonatomic, strong) NSMutableArray *declarationArray;
/**  */
@property (nonatomic, strong) comment *comment;
/** 评论数量 */
@property (nonatomic, strong) NSString *commentCount;
/** <#注释#> */
@property (nonatomic, strong) NSString *tokenid;
/** headerView */
@property (nonatomic, strong) UIView *headerView;
/** <#注释#> */
@property (nonatomic, assign) CGFloat cellHeight;

@end

static NSString *const cellID = @"Comment_cell";
@implementation CommentViewController

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)array {
    if (!_array) {
        _array = [NSMutableArray array];
    }
    return _array;
}
- (NSMutableArray *)likeArray {
    if (!_likeArray) {
        _likeArray = [NSMutableArray array];
    }
    return _likeArray;
}
- (NSMutableArray *)idArray {
    if (!_idArray) {
        _idArray = [NSMutableArray array];
    }
    return _idArray;
}
- (NSMutableArray *)nameArray {
    if (!_nameArray) {
        _nameArray = [NSMutableArray array];
    }
    return _nameArray;
}
- (NSMutableArray *)declarationArray {
    if (!_declarationArray) {
        _declarationArray = [NSMutableArray array];
    }
    return _declarationArray;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.translucent = NO;
    
    //接收点击用户头像的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didTapUserPicture:) name:@"didTapUserImage" object:nil];
    
    //接收点击评论用户头像的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didTapCommentUserPicture:) name:@"didTapCommentUserPicture" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"动态详情";
//    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
//    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"CommentCell" bundle:nil] forCellReuseIdentifier:cellID];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
 
    [self loadComment];
    
    
}
#pragma mark 接收到用户头像被点击的通知，跳转到用户详情界面
- (void)didTapUserPicture:(NSNotification *)note {
    
    CommunityUserViewController *userVc = [[CommunityUserViewController alloc] init];
    
    userVc.userID = note.userInfo[@"userID"];
    userVc.userName = note.userInfo[@"userName"];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"didTapUserImage" object:nil];

    [self.navigationController pushViewController:userVc animated:YES];
}

#pragma mark 接收到评论用户头像被点击的通知，跳转到用户详情界面
- (void)didTapCommentUserPicture:(NSNotification *)note {
    
    CommunityUserViewController *userVc = [[CommunityUserViewController alloc] init];
    
    userVc.userID = note.userInfo[@"commentUserID"];
    userVc.userName = note.userInfo[@"userName"];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"didTapCommentUserPicture" object:nil];
    [self.navigationController pushViewController:userVc animated:YES];
}

#pragma mark 处理键盘
- (void)keyboardWillChangeFrame:(NSNotification *)note {
    // 键盘显示\隐藏完毕的frame
    CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // 修改底部约束
    self.bottomSapce.constant = kHeight - frame.origin.y;
    // 动画时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    // 动画 及时刷新
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
    
}
//设置头部视图
- (void)setupHeader {
 
    UIView *header = [[UIView alloc] init];
    self.comment = self.array[0];
    
    CommunityCell *cell = [CommunityCell cell];
    cell.size = CGSizeMake(kWidth, self.comment.headerHeight);
    cell.comment = self.comment;
    
    [header addSubview:cell];

    header.height = cell.comment.headerHeight + 70 + 50;
    
    self.cellHeight = cell.comment.headerHeight;
    
    //分割线view
    UIView *CuttingLineView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.comment.headerHeight + 50, kWidth, 10)];
    CuttingLineView.backgroundColor = [UIColor colorWithRed:223/255.0 green:223/255.0 blue:223/255.0 alpha:0.6];
    //显示标题的view
    UIView *titleview = [[UIView alloc] initWithFrame:CGRectMake(0, cell.comment.headerHeight + 70, kWidth, 35)];
    titleview.backgroundColor = [UIColor whiteColor];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 100, 20)];
    titleLabel.text = [NSString stringWithFormat:@"%@条评论",self.commentCount];
    titleLabel.font = [UIFont systemFontOfSize:15];
    [titleview addSubview:titleLabel];
    
    
    [header addSubview:CuttingLineView];
    [header addSubview:titleview];
    self.headerView = header;
    self.tableView.tableHeaderView = self.headerView;
}

//设置点赞view
- (void)setUpLikeView {
    
    //点赞view
    UIView *likeView = [[UIView alloc] initWithFrame:CGRectMake(0, self.cellHeight, kWidth, 40)];
    NSLog(@"%f",self.cellHeight);
 
    ThumbButton *likeBtn = [[ThumbButton alloc] init];
    likeBtn.frame = CGRectMake(20, 5, 30, 30);
    //点赞按钮被点击回调事件
    likeBtn.buttonClick = ^(){
        NSLog(@"按钮被点击回调");
    };
    [likeView addSubview:likeBtn];
    NSInteger count = self.likeArray.count > 5 ? 5 : self.likeArray.count;
    for (int i = 0; i < count; i++) {

        UIButton *userbtn = [[UIButton alloc] initWithFrame:CGRectMake(60 + 50 * i, 0, 40, 40)];
        userbtn.tag = i + 10;
        [userbtn addTarget:self action:@selector(clickUserImage:) forControlEvents:UIControlEventTouchUpInside];
        userbtn.layer.cornerRadius = 20;
        userbtn.layer.masksToBounds = YES;
        userbtn.backgroundColor = [UIColor redColor];
        if (self.likeArray.count > 0) {
            [userbtn sd_setImageWithURL:[NSURL URLWithString:self.likeArray[i]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"coolStart_female_n"]];
        }
        
        [likeView addSubview:userbtn];
        
    }
    UIButton *moreBtn = [[UIButton alloc] initWithFrame:CGRectMake(kWidth - 60, 0, 40, 40)];
    [moreBtn addTarget:self action:@selector(lookMoreUser) forControlEvents:UIControlEventTouchUpInside];
    moreBtn.layer.cornerRadius = 20;
    moreBtn.layer.masksToBounds = YES;
    [moreBtn setImage:[UIImage imageNamed:@"find_other"] forState:UIControlStateNormal];
    [likeView addSubview:moreBtn];
    [self.headerView addSubview:likeView];
}

//点击点赞用户头像事件
- (void)clickUserImage:(UIButton *)btn {
    
    NSLog(@"%ld",btn.tag - 10);
    CommunityUserViewController *userVc = [[CommunityUserViewController alloc] init];
    userVc.userID = self.idArray[btn.tag - 10];
    userVc.userName = self.nameArray[btn.tag - 10];
    
    [self.navigationController pushViewController:userVc animated:YES];
    
}
//点击查看更多点赞用户
- (void)lookMoreUser {
    
    LikeInfoViewController *likeVc = [[LikeInfoViewController alloc] init];
    likeVc.nameArray = self.nameArray;
    likeVc.declarationArray = self.declarationArray;
    likeVc.urlArray = self.likeArray;
    likeVc.idArray = self.idArray;
    [self.navigationController pushViewController:likeVc animated:YES];
}

- (void)loadComment {
    
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"noteid"] = self.noteid;
    parame[@"tokenid"] = @"tokenid_undefined";
    parame[@"userid"] = @"5784da4c4925c70c581758a9";
    parame[@"time"] = @"1468392215182";

    
    [[QZRequestManager sharedManager] fetchDataWithUrl:@"http://ws.sythealth.com/ws/fit/newforum/note/getnoteandcommbyid" parameters:parame method:@"GET" needToCaches:NO fetchData:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",dic);
        
        self.commentCount = dic[@"data"][@"comm"];
        
        for (NSDictionary *commentDic in dic[@"data"][@"items"]) {
            comment *cot = [[comment alloc] init];
            [cot setValuesForKeysWithDictionary:commentDic];
            [self.dataArray addObject:cot];
        }
        
        comment *com = [[comment alloc] init];
        [com setValuesForKeysWithDictionary:dic[@"data"]];
        [self.array addObject:com];
        
    } updateUI:^{
        [self setupHeader];
        [self loadLikeUser];
        [self.tableView reloadData];
    }];
    
    
}

- (void)loadLikeUser {
    
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"feedid"] = self.noteid;
    parame[@"tokenid"] = @"tokenid_undefined";
    parame[@"page"] = @1;
    parame[@"pagesize"] = @9;
    
    [[QZRequestManager sharedManager] fetchDataWithUrl:@"http://ws.sythealth.com/ws/fit/v4_3/feed/getpraiseusers" parameters:parame method:@"GET" needToCaches:NO fetchData:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//        NSLog(@"%@",dic);
    
        for (NSDictionary *dict in dic[@"data"]) {
            
                if (dict[@"url"]) {
                    [self.likeArray addObject:dict[@"url"]];
                    [self.idArray addObject:dict[@"userid"]];
                    [self.nameArray addObject:dict[@"name"]];
                    [self.declarationArray addObject:dict[@"declaration"]];
            }
            
        }
        
    } updateUI:^{
        
        [self setUpLikeView];
    }];
}

- (void)requestTokenid {
    
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"desc"] = @"IOS";
    parame[@"mobileid"] = @"cac6e00a37a1d0549b10a69a5501fff2b38d11c5";
    parame[@"product"] = @"fit";
    parame[@"usersid"] = @"5784da4c4925c70c581758a9";
    
    [[QZRequestManager sharedManager] fetchDataWithUrl:@"http://ws.sythealth.com/ws/common/user/quicklogin" parameters:parame method:@"GET" needToCaches:NO fetchData:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//        NSLog(@"%@",dic);
        self.tokenid = dic[@"data"][@"tokenid"];
        
    } updateUI:^{
        
        [self PulicComment];
    }];
    
    
}
- (void)PulicComment {
    NSLog(@"%@",self.textField.text);
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"tokenid"] = self.tokenid;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    dic[@"usersid"] = @"5784da4c4925c70c581758a9";
    dic[@"noteid"] = self.community.ID;
    dic[@"receiveid"] = @" ";
    dic[@"content"] = self.textField.text;
    dic[@"flag"] = @0;
    parame[@"data"] = dic;
    NSLog(@"%@",parame);

    
    [[QZRequestManager sharedManager] fetchDataWithUrl:@"http://ws.sythealth.com/ws/fit/newforum/note/additem" parameters:parame method:@"POST" needToCaches:NO fetchData:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",dic);
        
    } updateUI:^{
        
        [self.tableView reloadData];
    }];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    cell.comment = self.dataArray[indexPath.row];
    
    
    return cell;
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    comment *com = self.dataArray[indexPath.row];

    return com.cellHeight;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [self.view endEditing:YES];
}
- (IBAction)sendBtn:(UIButton *)sender {
    
    [self requestTokenid];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
